package jnpf.i18n.util;

import jnpf.constant.model.MCode;
import jnpf.i18n.config.I18nProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 国际化工具类
 *
 * @date 2024/3/21 14:00
 */
@Component
public class I18nUtil {

    private static MessageSource messageSource;

    private static I18nProperties i18nProperties;

    @Autowired(required = false)
    public void setMessageSource(MessageSource messageSource) {
        I18nUtil.messageSource = messageSource;
    }

    @Autowired(required = false)
    public void setI18nProperties(I18nProperties i18nProperties) {
        I18nUtil.i18nProperties = i18nProperties;
    }

    public static String getMessageStr(String code, String message, Locale locale, Object... args) {
        if (messageSource == null) {
            return message == null ? code : message;
        }
        if (message != null) {
            return messageSource.getMessage(code, args, message, locale);
        }
        return messageSource.getMessage(code, args, locale);
    }

    public static String getMessageStr(String code, String message, Object... args) {
        Locale locale;
        try {
            locale = LocaleContextHolder.getLocale();
        } catch (Exception e) {
            locale = Locale.forLanguageTag(i18nProperties.getDefaultLanguage());
        }
        return getMessageStr(code, message, locale, args);
    }


    public static String getMessageStr(MCode mCode, Locale locale, Object... args) {
        return getMessageStr(mCode.getCode(), mCode.getDesc(), locale, args);
    }

    public static String getMessageStr(MCode mCode, Object... args) {
        return getMessageStr(mCode.getCode(), mCode.getDesc(), args);
    }


}
